import ajax from 'uni-ajax'
import store from '../store/index.js'
import { TOKEN, XWWWFROMURLENCODED, baseURL, FORMURLENCODED, NODETYPE } from './constant.js'
const config = {
  baseURL,
  timeout: 5000
}
// 创建请求实例
const instance = ajax.create(config)
// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    config.header['TerminalType'] = 'APPLET'
    console.log(store.state.vuex_token, 'store.state.vuex_token')
    if (store.state.vuex_token) {
      config.header[TOKEN] = store.state.vuex_token
      config.header[NODETYPE] = store.state.nodeType
      if (config.type === FORMURLENCODED) {
        config.header['Content-Type'] = XWWWFROMURLENCODED
      }
    } else {
      if (config.type === XWWWFROMURLENCODED) {
        config.header['Content-Type'] = XWWWFROMURLENCODED
        if (store.state.keepLogin) {
          config.header['keepLogin'] = 'keep'
        }
      } else {
        if (config.notoken) return config
        console.error('no token, back to login page')
        let routes = getCurrentPages()
        if (!routes[routes.length - 1].route.includes('login')) {
          // uni.navigateTo({
          //   url: '/pages/login/login'
          // })
        }
        return false
      }
    }

    for (const key in config.params) {
      const element = config.params[key]
      if (element === null || element === undefined) {
        delete config.params[key]
      }
    }
    if (config.params) {
      // 处理query数组
      config.paramsSerializer = params => qs.stringify(params, { arrayFormat: 'repeat' })
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 400001) {
      console.log('登录信息失效')
      store.dispatch('resetToken')
      console.log(store, 'store')
      let routes = getCurrentPages()
      if (!routes[routes.length - 1].route.includes('login')) {
        // uni.navigateTo({
        //   url: '/pages/login/login'
        // })
      }
      return false
    }
    if (res.code !== 200) {
      console.log(response.config.url, '\n', response.data?.msg, response.header?.traceId)
    }
    return response.data
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

export default instance
